package srv

import (
	"background/http/api/dto"
	"background/model/back/entity"
	"background/model/back/repo"
	"background/utilx/cachex"
	"context"
	"github.com/redis/go-redis/v9"
	"gorm.io/gen"
)

type CloudServer struct {
	db     repo.Query
	bucket cachex.RedisBucket
	redisx *redis.Client
}

func newCloudServer(db repo.Query, bucket cachex.RedisBucket) CloudServer {
	redisx := bucket.GetClient(entity.CacheTypeCategory)
	return CloudServer{db: db, bucket: bucket, redisx: redisx}
}

func (r CloudServer) DelById(ctx context.Context, id int64) (gen.ResultInfo, error) {
	return r.db.CloudServer.WithContext(ctx).Where(repo.CloudServer.ID.Eq(id)).Delete()
}
func (r CloudServer) GetById(ctx context.Context, id int64) (*entity.CloudServer, error) {
	userInfo, err := r.db.CloudServer.WithContext(ctx).Where(repo.CloudServer.ID.Eq(id)).First()
	if err != nil {
		return nil, err
	}
	return userInfo, err
}
func (r CloudServer) InsertOne(ctx context.Context, rec entity.CloudServer) error {
	return r.db.CloudServer.WithContext(ctx).Create(&rec)
}
func (r CloudServer) GetBySelf(ctx context.Context, rec dto.SearchWithPage[entity.CloudServer]) (dto.PageResult[entity.CloudServer], error) {
	//u := rec.Act
	page := rec.PageInfo
	do := r.db.CloudServer.WithContext(ctx).Debug()

	if len(rec.Data.Name) > 0 {
		do = do.Where(repo.CloudServer.Name.Like(rec.Data.Name + "%"))
	}
	if len(rec.Data.Host) > 0 {
		do = do.Where(repo.CloudServer.Host.Like(rec.Data.Host + "%"))
	}
	if len(rec.Data.Network) > 0 {
		do = do.Where(repo.CloudServer.Network.Like(rec.Data.Network + "%"))
	}
	if len(rec.Data.Type) > 0 {
		do = do.Where(repo.CloudServer.Type.Like(rec.Data.Type + "%"))
	}
	if rec.Data.IsOnline > -1 {
		do = do.Where(repo.CloudServer.IsOnline.Eq(rec.Data.IsOnline))
	}
	if rec.Data.TLS > -1 {
		do = do.Where(repo.CloudServer.TLS.Eq(rec.Data.TLS))
	}

	byPage, i, err := do.Order(repo.CloudServer.Sort).FindByPage(int(page.Start()), int(page.PageSize))
	if err != nil {
		return dto.PageResult[entity.CloudServer]{}, err
	}
	return dto.PageResult[entity.CloudServer]{
		Items: byPage,
		Total: i,
	}, nil
}
func (r CloudServer) UpdateById(ctx context.Context, u *entity.CloudServer) error {
	err := r.db.CloudServer.WithContext(ctx).Where(repo.CloudServer.ID.Eq(u.ID)).Save(u)
	if err != nil {
		return err
	}
	return nil
}
func (r CloudServer) GetBySelfCache(ctx context.Context, flush bool, rec dto.SearchWithPage[entity.CloudServer]) (dto.PageResult[entity.CloudServer], error) {
	aopx, err := cachex.Aopx[dto.PageResult[entity.CloudServer]](false, flush, r.redisx,
		entity.CacheKey(entity.CacheTypeCategory, rec), Dur, func() (dto.PageResult[entity.CloudServer], error) {
			return r.GetBySelf(ctx, rec)
		})
	if err != nil {
		return dto.PageResult[entity.CloudServer]{}, err
	}
	return aopx, nil
}
